package com.da.lon.wang.xlg.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.da.lon.wang.xlg.MyApplication;
import com.da.lon.wang.xlg.R;
import com.da.lon.wang.xlg.adapter.SearchGridAdapter;
import com.da.lon.wang.xlg.adapter.SearchListAdapter;
import com.da.lon.wang.xlg.bean.ResultSearchBean;
import com.da.lon.wang.xlg.bean.ResultSearchBean.ResultSearchListBean.SearchResultCategory;
import com.da.lon.wang.xlg.bean.ResultSearchBean.ResultSearchListBean.SearchResultList;
import com.da.lon.wang.xlg.bean.ResultSearchBean.ResultSearchListBean.SearchResultOther;
import com.da.lon.wang.xlg.bean.SerializableMap;
import com.da.lon.wang.xlg.constants.PreferencesConfig;
import com.da.lon.wang.xlg.constants.XLGConstants;
import com.da.lon.wang.xlg.http.HttpLoader;
import com.da.lon.wang.xlg.http.HttpLoader.OnWebLoadListener;
import com.da.lon.wang.xlg.pulltorefresh.library.PullToRefreshBase;
import com.da.lon.wang.xlg.pulltorefresh.library.PullToRefreshBase.Mode;
import com.da.lon.wang.xlg.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.da.lon.wang.xlg.pulltorefresh.library.PullToRefreshGridView;
import com.da.lon.wang.xlg.util.DateUtils;
import com.da.lon.wang.xlg.util.LogUtils;
import com.da.lon.wang.xlg.util.PreferenceUtils;
import com.da.lon.wang.xlg.util.Utils;
import com.da.lon.wang.xlg.util.XLGDataUtils;
import com.umeng.analytics.MobclickAgent;

import net.tsz.afinal.http.AjaxParams;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


public class ResultSearchActivity extends BaseActivity implements
        OnRefreshListener2<GridView>, OnClickListener {

    Map<String, String> pare_map = null;
    private Context context;
    private String searchContent = null;
    private HttpLoader<ResultSearchBean> loader;
    private List<SearchResultList> list = new ArrayList<SearchResultList>();
    private ArrayList<SearchResultOther> otherlist = new ArrayList<SearchResultOther>();
    private ArrayList<SearchResultCategory> categorylist = new ArrayList<SearchResultCategory>();
    private PullToRefreshGridView gridView;
    private BaseAdapter adapter;
    private int page;
    private String orderby = "moren";
    /**
     * 分类进来的 cid
     */
    private String cid = null;
    private String sattr = null;
    private String sattr1 = null;
    private String id = null;
    private String user_key = null;
    private String price1 = null;
    private String price2 = null;
    private TextView rqTextView;
    private TextView xlTextView;
    private TextView xpTextView;
    private CheckBox jgCheckBox;
    private TextView flImageView;
    private ImageView search_type;
    private EditText etSearch;
    private ImageButton leftButton;
    private ImageView ivDeleteSearch;
    private int showType = 1;
    private boolean isFirst = true;
    private boolean flg = true;
    /**
     * 筛选回来的Cid
     */
    private String chooesCid = null;
    private String search_sattr;
    private LinearLayout result_search_ll;

    private TextView search_title_tv;

    private boolean choessxl;

    @Override
    protected void onResume() {
        super.onResume();
        setFilterResult();
        if (flg) {
            initData(1);
        }
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
        MyApplication.hideInputWindow(etSearch, this);
    }

    private SharedPreferences mUserInfoSp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ocoffee_result_search);
        mUserInfoSp = MyApplication.getInstance().getSharedPreferences("user_info", Context.MODE_PRIVATE);
        context = this;
        try {
            MyApplication.getInstance().setPrice_hight("");
            MyApplication.getInstance().setPrice_small("");
            Intent intent = getIntent();
            if (intent != null) {
                searchContent = intent.getStringExtra("searchContent");
                choessxl = intent.getBooleanExtra("choessxl", false);
                cid = intent.getStringExtra("cid");
                orderby = intent.getStringExtra("orderby");
            }
            if (intent != null && intent.getExtras() != null
                    && intent.getExtras().getSerializable("map") != null) {
                SerializableMap serializableMap = (SerializableMap) intent
                        .getExtras().getSerializable("map");
                pare_map = serializableMap.getMap();
            }

            PreferenceUtils.getInstance().SetSettingString(
                    PreferencesConfig.CID, "");
            search_sattr = PreferenceUtils.getInstance().getSettingStr(
                    PreferencesConfig.SEARCH_SATTR, "");
            initView();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void showTypeChange() {
        switch (showType) {
            case 1:


                search_type.setBackgroundResource(R.drawable.search_type_grid);
                gridView.getRefreshableView().setNumColumns(2);
                gridView.getRefreshableView().setVerticalSpacing(10);
                adapter = new SearchGridAdapter(list, context);
                gridView.getRefreshableView().setAdapter(adapter);


                break;

            case 0:


                search_type.setBackgroundResource(R.drawable.search_type_list);
                gridView.getRefreshableView().setVerticalSpacing(0);
                gridView.getRefreshableView().setNumColumns(1);
                adapter = new SearchListAdapter(list, context);
                gridView.getRefreshableView().setAdapter(adapter);


                break;
        }
        adapter.notifyDataSetChanged();
    }

    private void initView() {

        rqTextView = (TextView) findViewById(R.id.search_rq);
        xlTextView = (TextView) findViewById(R.id.search_xl);
        xpTextView = (TextView) findViewById(R.id.search_xp);
        jgCheckBox = (CheckBox) findViewById(R.id.search_jg);
        flImageView = (TextView) findViewById(R.id.search_fl);

        result_search_ll = (LinearLayout) findViewById(R.id.result_search_ll);
        search_title_tv = (TextView) findViewById(R.id.search_title_tv);
        etSearch = (EditText) findViewById(R.id.et_search);
        leftButton = (ImageButton) findViewById(R.id.resultsearch_left);
        ivDeleteSearch = (ImageView) findViewById(R.id.iv_delete_search);

        search_type = (ImageView) findViewById(R.id.search_type);
        search_type.setOnClickListener(this);
        leftButton.setOnClickListener(this);
        ivDeleteSearch.setOnClickListener(this);

        gridView = (PullToRefreshGridView) findViewById(R.id.ouka_search_gridview);
        gridView.setMode(Mode.BOTH);
        gridView.setOnRefreshListener(this);
        gridView.getRefreshableView().setOnItemClickListener(
                new OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> parent, View view,
                                            int position, long id) {
                        if (!MyApplication.isNetworkAvailable(context)) {
                            return;
                        }
                        flg = false;
                        PreferenceUtils.getInstance().SetSettingString(
                                PreferencesConfig.CID, "");
                        String product_number = list.get(position).getProduct_number();
                        Intent intent = new Intent(context,
                                ProductsActivity.class);
                        PreferenceUtils.getInstance().SetSettingString(
                                PreferencesConfig.PRODUCT_NUMBER,
                                product_number);
                        startActivity(intent);
                    }
                });

        etSearch.setText(searchContent);

        etSearch.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub
            }
        });

        etSearch.setOnEditorActionListener(new OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId,
                                          KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    // 先隐藏键盘
                    MyApplication.hideInputWindow(etSearch,
                            ResultSearchActivity.this);
                    // 搜索
                    searchContent = etSearch.getText().toString().trim();
                    isFirst = true;
                    search_sattr = "";
                    Utils.clearFilter(search_sattr);
                    setFilterResult();
                    cid = "";
                    if (TextUtils.isEmpty(searchContent)) {
                        initData(1);
                    } else {
                        initData(1);
                        DateUtils.saveSearchHistory(searchContent, context);
                    }
                    return true;
                }
                return false;
            }
        });

        rqTextView.setOnClickListener(this);
        xlTextView.setOnClickListener(this);
        xpTextView.setOnClickListener(this);
        flImageView.setOnClickListener(this);
        if (choessxl) {
            // 点击销量进来
            xlTextView.setTextColor(Color.parseColor("#FF3E47"));
        } else if (isFirst) {
            rqTextView.setTextColor(Color.parseColor("#FF3E47"));
        }
        jgCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                                         boolean isChecked) {
                // TODO Auto-generated method stub
                PreferenceUtils.getInstance().SetSettingString(
                        PreferencesConfig.SEARCH_SATTR, "");
                if (isChecked) {

                    rqTextView.setTextColor(Color.parseColor("#333333"));
                    xlTextView.setTextColor(Color.parseColor("#333333"));
                    xpTextView.setTextColor(Color.parseColor("#333333"));
                    jgCheckBox.setTextColor(Color.parseColor("#FF3E47"));

                    Drawable drawable = getResources().getDrawable(
                            R.drawable.ocoffee_search_pic2);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(),
                            drawable.getMinimumHeight());
                    jgCheckBox.setCompoundDrawables(null, null, drawable, null);

                    orderby = "price_";
                    initData(1);
                } else {

                    rqTextView.setTextColor(Color.parseColor("#333333"));
                    xlTextView.setTextColor(Color.parseColor("#333333"));
                    xpTextView.setTextColor(Color.parseColor("#333333"));
                    jgCheckBox.setTextColor(Color.parseColor("#FF3E47"));

                    Drawable drawable = getResources().getDrawable(
                            R.drawable.ocoffee_search_pic3);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(),
                            drawable.getMinimumHeight());
                    jgCheckBox.setCompoundDrawables(null, null, drawable, null);

                    orderby = "price+";
                    initData(1);
                }
            }

        });


        if (null != pare_map && pare_map.size() != 0) {
            for (String key : pare_map.keySet()) {
                if (key.equals("title")) {
                    result_search_ll.setVisibility(View.GONE);
                    search_title_tv.setVisibility(View.VISIBLE);
                    search_title_tv.setText(pare_map.get(key));
                    if (pare_map.get(key).equals("销量榜")) {
                        showType = 0;
                        showTypeChange();
                    }
                }
            }
        }

    }


    private void initData(final int flg) {
        try {
            if (flg == 1) {
                showTypeChange();
                page = 1;
            } else if (flg == 2) {
                page = page + 1;
            }
            loader = new HttpLoader<ResultSearchBean>(context, XLGConstants.URL
                    + "Search-index?", ResultSearchBean.class, 30 * 1000);
            AjaxParams params = new AjaxParams();
            params.put("token", XLGDataUtils.encrypt2MD5("Search" + "2015#$%"
                    + "index"));
            params.put("id", id);
            params.put("user_key", user_key);
            params.put("name", searchContent);
            params.put("p", page + "");
            params.put("orderby", orderby);
            if (chooesCid != null && !chooesCid.equals("")) {
                params.put("cid", chooesCid);
            } else {
                params.put("cid", cid);
            }

            if (MyApplication.getInstance().getPrice_hight() != null
                    && !MyApplication.getInstance().getPrice_hight().trim()
                    .equals("")) {
                params.put("price2", MyApplication.getInstance()
                        .getPrice_hight());
            }
            if (MyApplication.getInstance().getPrice_small() != null
                    && !MyApplication.getInstance().getPrice_small().trim()
                    .equals("")) {
                params.put("price1", MyApplication.getInstance()
                        .getPrice_small());
            }

            if (sattr != null && !"".equals(sattr)) {
                params.put("sattr", sattr);
            }
            params.put("version", "21");

            if (pare_map != null) {
                for (String key : pare_map.keySet()) {
                    LogUtils.v("key= " + key + " and value= "
                            + pare_map.get(key));
                    params.remove(key);
                    params.put(key, pare_map.get(key));
                }
            }

            loader.loadData(params);
            loader.setManagerListener(new OnWebLoadListener<ResultSearchBean>() {

                @Override
                public void OnStart() {
                    showDialog();
                }

                @Override
                public void OnError(String error) {
                    dismissDialog();
                    MyApplication.hideInputWindow(etSearch,
                            ResultSearchActivity.this);
                    new Handler().post(new Runnable() {

                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            gridView.onRefreshComplete();
                        }
                    });
                }

                @Override
                public void onSuccess(ResultSearchBean t) {
                    dismissDialog();
                    MyApplication.hideInputWindow(etSearch,
                            ResultSearchActivity.this);
                    new Handler().post(new Runnable() {

                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            gridView.onRefreshComplete();
                        }
                    });
                    if (t != null && t.getCode().equals("000000")
                            && t.getResult().getList() != null) {
                        if (flg == 1 && t.getResult().getList().isEmpty()) {
                            Toast.makeText(ResultSearchActivity.this,
                                    "亲，没有搜到你想要的商品！", Toast.LENGTH_SHORT).show();
                            list.clear();
                            adapter.notifyDataSetChanged();
                            if (isFirst) {
                                MyApplication.getInstance().setOtherlist(null);
                                MyApplication.getInstance().setCategorylist(
                                        null);
                            }
                        } else {
                            if (flg == 1) {
                                list.clear();
                            }
                            list.addAll(t.getResult().getList());
                            if (isFirst) {
                                otherlist.clear();
                                otherlist.addAll(t.getResult().getOther());
                                MyApplication.getInstance().setOtherlist(
                                        t.getResult().getOther());
                                categorylist.clear();
                                categorylist
                                        .addAll(t.getResult().getCategory());
                                MyApplication.getInstance().setCategorylist(
                                        t.getResult().getCategory());
                                isFirst = false;
                            }
                            adapter.notifyDataSetChanged();
                        }
                    } else {
                        if (t != null) {
                            Toast.makeText(ResultSearchActivity.this,
                                    t.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<GridView> refreshView) {
        initData(1);
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<GridView> refreshView) {
        initData(2);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.search_rq:
                rqTextView.setTextColor(Color.parseColor("#FF3E47"));
                xlTextView.setTextColor(Color.parseColor("#333333"));
                xpTextView.setTextColor(Color.parseColor("#333333"));
                jgCheckBox.setTextColor(Color.parseColor("#333333"));

                Drawable drawable = getResources().getDrawable(
                        R.drawable.ocoffee_search_pic1);
                drawable.setBounds(0, 0, drawable.getMinimumWidth(),
                        drawable.getMinimumHeight());
                jgCheckBox.setCompoundDrawables(null, null, drawable, null);

                orderby = "moren";
                initData(1);
                break;

            case R.id.search_xl:

                rqTextView.setTextColor(Color.parseColor("#333333"));
                xlTextView.setTextColor(Color.parseColor("#FF3E47"));
                xpTextView.setTextColor(Color.parseColor("#333333"));
                jgCheckBox.setTextColor(Color.parseColor("#333333"));

                Drawable drawable1 = getResources().getDrawable(
                        R.drawable.ocoffee_search_pic1);
                drawable1.setBounds(0, 0, drawable1.getMinimumWidth(),
                        drawable1.getMinimumHeight());
                jgCheckBox.setCompoundDrawables(null, null, drawable1, null);

                orderby = "xl_";
                initData(1);
                break;

            case R.id.search_xp:

                rqTextView.setTextColor(Color.parseColor("#333333"));
                xlTextView.setTextColor(Color.parseColor("#333333"));
                xpTextView.setTextColor(Color.parseColor("#FF3E47"));
                jgCheckBox.setTextColor(Color.parseColor("#333333"));

                Drawable drawable11 = getResources().getDrawable(
                        R.drawable.ocoffee_search_pic1);
                drawable11.setBounds(0, 0, drawable11.getMinimumWidth(),
                        drawable11.getMinimumHeight());
                jgCheckBox.setCompoundDrawables(null, null, drawable11, null);

                orderby = "sjtime+";
                initData(1);
                break;

            case R.id.search_fl:
                flg = true;
                Intent intent = new Intent(ResultSearchActivity.this,
                        FilterActivity.class);
                intent.putExtra("otherlist", (Serializable) MyApplication
                        .getInstance().getOtherlist());
                intent.putExtra("search_sattr", search_sattr);
                intent.putExtra("categorylist", (Serializable) MyApplication
                        .getInstance().getCategorylist());
                startActivity(intent);
                overridePendingTransition(R.anim.activity_in_from_right,
                        R.anim.activity_out_to_left);
                break;

            case R.id.resultsearch_left:
                MyApplication.hideInputWindow(etSearch, ResultSearchActivity.this);
                finish();
                break;

            case R.id.iv_delete_search:// 清空搜索内容

                // etSearch.setText("");
                // ivDeleteSearch.setVisibility(View.INVISIBLE);

                MyApplication.hideInputWindow(etSearch, ResultSearchActivity.this);
                // 搜索
                searchContent = etSearch.getText().toString().trim();
                isFirst = true;
                search_sattr = "";
                Utils.clearFilter(search_sattr);
                setFilterResult();
                cid = "";
                if (TextUtils.isEmpty(searchContent)) {
                    initData(1);
                } else {
                    initData(1);
                    DateUtils.saveSearchHistory(searchContent, context);
                }

                break;

            case R.id.search_type:

                if (showType == 1) {
                    showType = 0;
                } else {
                    showType = 1;
                }
                showTypeChange();
                break;

            default:
                break;
        }

    }

    /**
     * 设置筛选结果
     */
    private void setFilterResult() {
        try {
            sattr1 = PreferenceUtils.getInstance().getSettingStr(
                    PreferencesConfig.SEARCH_SATTR, "");
            if (sattr1 == null || sattr1.equals("")) {
                sattr = "";
            } else {
                if (sattr1.indexOf("/") != -1) {
                    sattr = sattr1.replaceAll("/", "_");
                } else {
                    sattr = sattr1;
                }
            }
            id = mUserInfoSp.getString("user_id", "");
            user_key = mUserInfoSp.getString("user_key", "");
            if (flg) {
                String settingStr = PreferenceUtils.getInstance()
                        .getSettingStr(PreferencesConfig.CID, "");
                if (!settingStr.equals("") && settingStr.trim().length() > 0) {
                    chooesCid = settingStr;
                } else {
                    chooesCid = "";
                }

                // initData(1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        PreferenceUtils.getInstance().SetSettingString(
                PreferencesConfig.SEARCH_SATTR, "");
    }
}
